import database from './database.js'
import { typeCall } from '@/assets/js/util.js'
const DBNAME = 'UNI_POLYMERIZE_DATABASE'//数据库名称
const config = {
	local: 'LOCAL_RESOURCE_TABLE',//本地资源表名
	local_mark: 'LOCAL_RESOURCE_MARK_TABLE',//本地资源标记表名
	record: 'RESOURCE_RECORD_TABLE',//资源历史记录表名
	history: 'BROWSER_HISTORY',//浏览器记录
	mark: 'RESOURCE_MARK_TABLE',//资源书签表名
	collection: 'RESOURCE_COLLECTION_TABLE',//资源收藏表名
	followee: 'RESOURCE_FOLLOWEE_TABLE',//关注表
	shortcut: 'SHORTCUT_TABLE',//快捷方式表名
	download: 'DOWNLOAD_RECORD_TABLE',//下载记录表名
	subscribe: 'DOWNLOAD_SUBSCRIBE_TABLE',//线上订阅表名
	source: 'SOURCE_TABLE',//源规则存储表
}
const openDB = function () {
	return new Promise((resolve, reject) => {
		database.open({
			name: DBNAME,
			success: function (e) {
				resolve(e)
			},
			fail: function (e) {
				reject(e)
			}
		})
	})
}
const closeDB = function () {
	return new Promise((resolve, reject) => {
		database.close({
			name: DBNAME,
			success: function (e) {
				resolve(e)
			},
			fail: function (e) {
				reject(e)
			}
		})
	})
}
const isOpenDB = function () {
	return database.isOpen(DBNAME)
}
//创建表
const create = function (TABLE, data) {
	return new Promise((resolve, reject) => {
		database.executeSql({
			name: DBNAME,
			sql: `CREATE TABLE if not exists ${config[TABLE]} (${data.join(',')})`,
			success: function (e) {
				resolve(e)
			},
			fail: function (e) {
				reject(e)
			}
		})
	})
}
//插入数据
const insert = function (TABLE, data) {
	const list = typeCall(data) == 'Array' ? data : [data]
	const keys = Object.keys(list[0]).map(key => htd(key))
	const arr = list.map(item => {
		const ks = Object.keys(item)
		return ' select ' + ks.map(k => ctb(item[k])).join(',')
	})
	const selectStr = arr.join(' union')
	return new Promise((resolve, reject) => {
		database.executeSql({
			name: DBNAME,
			sql: 'insert or replace into ' + config[TABLE] + ' (' + keys.join(',') + ') ' + selectStr,
			success: function (e) {
				resolve(e)
			},
			fail: function (e) {
				reject(e)
			}
		})
	})
}
//更新数据
const update = function (TABLE, data, whereStr) {
	const arr = Object.keys(data).map(key => htd(key) + ' = ' + ctb(data[key]) + ', ' )
	const selectStr = arr.join('')
	return new Promise((resolve, reject) => {
		database.executeSql({
			name: DBNAME,
			sql: 'update ' + config[TABLE] + ' set ' + selectStr + 'update_time = CURRENT_TIMESTAMP' + (whereStr ? ' where ' + whereStr : ''),
			success: function (e) {
				resolve(e)
			},
			fail: function (e) {
				reject(e)
			}
		})
	})
}

//删除数据
const remove = function (TABLE, whereStr) {
	return new Promise((resolve, reject) => {
		database.executeSql({
			name: DBNAME,
			sql: 'delete from ' + config[TABLE] + (whereStr ? ' where ' + whereStr : ''),
			success: function (e) {
				resolve(e)
			},
			fail: function (e) {
				reject(e)
			}
		})
	})
}

//查询数据
const select = function (TABLE, whereStr, orderBy = 'update_time desc', limit) {
	return new Promise((resolve, reject) => {
		database.selectSql({
			name: DBNAME,
			sql: 'select * from ' + config[TABLE] + (whereStr ? ' where ' + whereStr : '') + (orderBy ? ' order by ' + orderBy : '') + (limit ? ' limit ' + limit : ''),
			success: function (e) {
				database.selectSql({
					name: DBNAME,
					sql: 'select count(*) from ' + config[TABLE] + (whereStr ? ' where ' + whereStr : ''),
					success: function (count) {
						resolve({
							list: e,
							count: count[0]['count(*)']
						})
					},
					fail: function (e) {
						reject(e)
					}
				})
			},
			fail: function (e) {
				reject(e)
			}
		})
	})
}

const init = async function () {
	try{
		const local = [
			'id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE',
			'name VARCHAR(50) NOT NULL',
			'path VARCHAR(100) UNIQUE NOT NULL',
			'size VARCHAR(20) NOT NULL',
			'type VARCHAR(10) NOT NULL',
			'position VARCHAR(20)',
			'progress VARCHAR(10)',
			'create_time timestamp DEFAULT CURRENT_TIMESTAMP',
			'update_time timestamp DEFAULT CURRENT_TIMESTAMP'
		]
		await create('local', local)
		const local_mark = [
			'id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE',
			'resource_id INTEGER NOT NULL',
			'title VARCHAR(50) NOT NULL',
			'position VARCHAR(20) NOT NULL',
			'create_time timestamp DEFAULT CURRENT_TIMESTAMP',
			'update_time timestamp DEFAULT CURRENT_TIMESTAMP'
		]
		await create('local_mark', local_mark)
		const record = [
			'id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE',
			'unique_id VARCHAR(1000) NOT NULL',
			'url VARCHAR(1000) NOT NULL',
			'title VARCHAR(50) NOT NULL',
			'cover VARCHAR(1000) NOT NULL',
			'current VARCHAR(10)',
			'position VARCHAR(10)',
			'progress VARCHAR(10)',
			'current_title VARCHAR(50)',
			'is_adult INT(1) DEFAULT 0',
			'source_id VARCHAR(20)',
			'create_time timestamp DEFAULT CURRENT_TIMESTAMP',
			'update_time timestamp DEFAULT CURRENT_TIMESTAMP'
		]
		await create('record', record)
		const mark = [
			'id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE',
			'unique_id VARCHAR(1000) NOT NULL',
			'title VARCHAR(50) NOT NULL',
			'current VARCHAR(10)',
			'position VARCHAR(10)',
			'create_time timestamp DEFAULT CURRENT_TIMESTAMP',
			'update_time timestamp DEFAULT CURRENT_TIMESTAMP'
		]
		await create('mark', mark)
		const collection = [
			'id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE',
			'unique_id VARCHAR(1000) NOT NULL',
			'url VARCHAR(1000) NOT NULL',
			'title VARCHAR(50) NOT NULL',
			'cover VARCHAR(1000)',
			'is_adult INT(1) DEFAULT 0',
			'source_id VARCHAR(20)',
			'create_time timestamp DEFAULT CURRENT_TIMESTAMP',
			'update_time timestamp DEFAULT CURRENT_TIMESTAMP'
		]
		await create('collection', collection)
		const followee = [
			'id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE',
			'unique_id VARCHAR(1000) NOT NULL',
			'url VARCHAR(1000) NOT NULL',
			'title VARCHAR(50) NOT NULL',
			'avatar VARCHAR(1000)',
			'is_adult INT(1) DEFAULT 0',
			'source_id VARCHAR(20)',
			'create_time timestamp DEFAULT CURRENT_TIMESTAMP',
			'update_time timestamp DEFAULT CURRENT_TIMESTAMP'
		]
		await create('followee', followee)
		const history = [
			'id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE',
			'title VARCHAR(50) NOT NULL',
			'href VARCHAR(1000)',
			'is_adult INT(1) DEFAULT 0',
			'create_time timestamp DEFAULT CURRENT_TIMESTAMP',
			'update_time timestamp DEFAULT CURRENT_TIMESTAMP'
		]
		await create('history', history)
		const shortcut = [
			'id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE',
			'title VARCHAR(50) NOT NULL',
			'logo VARCHAR(1000) NOT NULL',
			'url VARCHAR(1000) NOT NULL',
			'is_adult INT(1) DEFAULT 0',
			'create_time timestamp DEFAULT CURRENT_TIMESTAMP',
			'update_time timestamp DEFAULT CURRENT_TIMESTAMP'
		]
		await create('shortcut', shortcut)
		const download = [
			'id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE',
			'title VARCHAR(50) NOT NULL',
			'url VARCHAR(1000) NOT NULL',
			'file_path VARCHAR(100)',
			'state INT(1) DEFAULT 0',
			'is_adult INT(1) DEFAULT 0',
			'create_time timestamp DEFAULT CURRENT_TIMESTAMP',
			'update_time timestamp DEFAULT CURRENT_TIMESTAMP'
		]
		await create('download', download)
		const subscribe = [
			'id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE',
			'title VARCHAR(50) NOT NULL',
			'url VARCHAR(1000) NOT NULL',
			'is_adult INT(1) DEFAULT 0',
			'create_time timestamp DEFAULT CURRENT_TIMESTAMP',
			'update_time timestamp DEFAULT CURRENT_TIMESTAMP'
		]
		await create('subscribe', subscribe)
		const source = [
			'id INTEGER PRIMARY KEY AUTOINCREMENT UNIQUE',
			'rule TEXT NOT NULL',
			'is_adult INT(1) DEFAULT 0',
			'source_id VARCHAR(20)',
			'create_time timestamp DEFAULT CURRENT_TIMESTAMP',
			'update_time timestamp DEFAULT CURRENT_TIMESTAMP'
		]
		await create('source', source)
		return true
	}catch(e){
		return e
		//TODO handle the exception
	}
}

//字符转数据库字符
const ctb = function (char) {
	return typeof char == 'string' ? `"${char}"` : typeof char == 'boolean' ? (char ? 1 : 0) : char
}

//驼峰法转下横线
const htd = function (name) {
	return name.replace(/\B([A-Z])/g, '_$1').toLowerCase()
}

module.exports = {
	openDB,
	closeDB,
	isOpenDB,
	create,
	select,
	insert,
	update,
	remove,
	init
}